import { ref, watch, WatchStopHandle } from 'vue'

export default class BatchWatch {
  private watches: (() => WatchStopHandle)[]
  private running: WatchStopHandle[] = []
  constructor(immediate: boolean, watches: (() => WatchStopHandle)[]) {
    if (watches == null || watches.length === 0) throw new Error('没有watch启动函数!')
    this.watches = watches
    if (immediate) this.start()
  }
  public start() {
    for (const [index, watchStartHandler] of this.watches.entries()) {
      // 看是否有正在运行
      const instance = this.running[index]
      // 如果没有运行起来就运行
      if (instance == null) this.running[index] = watchStartHandler()
    }
  }
  public stop() {
    for (const instance of this.running) instance != null && instance()
    this.running = []
  }
}
